// pages/login/login.js
import Message from 'tdesign-miniprogram/message/index';
var app = getApp();
// var tokenConstant = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Nn0.0C-pklGl8S9T6aiJgxZAudKW3x2gbisxKUaxiRj2WbA";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        visible: false, // 弹出层
        veriCode: '',
    },
    getUserInfo() {
        console.log('acquiring user info');
        wx.request({
            url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/user?Action=GetUserInfo`,
            method: 'GET',
            header: {
                "Content-Type": "application/json",
                "x-api-key": wx.getStorageSync('token')
            },
            success(res) {
                console.log("fetched user info successfully", res);
                wx.setStorageSync('userInfo', res.data.message);
            },
            fail(res) {
                console.log("fetch user info failed", res);
            }
        })
    },
    // 患者登录
    patientLogin: function () {
        console.log("patient login");
        wx.login({
            success: (res) => {
                console.log(res.code);
                wx.request({
                    url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/auth?Action=LogIn`,
                    method: 'POST',
                    header: {
                        "Content-Type": "application/json"
                    },
                    data: {
                        "role": 0,
                        "wechatId": res.code,
                    },
                    success: (res) => {
                        console.log(res);
                        if (res.statusCode == 200) {
                            wx.setStorageSync('token', res.data.message.token);
                            this.getUserInfo();
                            wx.removeStorageSync('role');
                            wx.setStorageSync('role', "patient");

                            wx.request({
                                url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/user?Action=HasUser`,
                                method: 'POST',
                                header: {
                                    "Content-Type": "application/json",
                                    "x-api-key": wx.getStorageSync('token')
                                },
                                data: {
                                    "username": res.data.message.username,
                                },
                                success: (res) => {
                                    console.log(res);
                                    if (res.statusCode == 200) {
                                        console.log(res.data.message)
                                        const isFirstLogin = !res.data.message.has_user;

                                        // 检查是否是第一次登录
                                        if (isFirstLogin) {
                                            // 如果是第一次登录，设置标志并跳转到另一个页面
                                            wx.setStorageSync('isFirstLogin', true);
                                            wx.navigateTo({
                                                url: '/pages/firstLogin/firstLogin'
                                            });
                                        } else {
                                            // 如果不是第一次登录，跳转到正常页面
                                            setTimeout(() => {
                                                wx.switchTab({
                                                    url: '/pages/foodrecord/foodrecord',
                                                });
                                            }, 300);
                                        }
                                    }
                                },
                                fail: (res) => {
                                    console.log("信息获取出现错误！");
                                    wx.showModal({
                                        title: '信息获取错误',
                                        content: '抱歉 我们将尽快检修',
                                    });
                                }
                            });
                        } else {
                            wx.showModal({
                                title: '登录错误',
                                content: "抱歉，我们将尽快检修",
                            });
                        }
                    },
                    fail: (res) => {
                        console.log("登录出现错误！");
                        wx.showModal({
                            title: '登录错误',
                            content: '抱歉 我们将尽快检修',
                        });
                    }
                });
            }
        });
    },

    // 医生登录
    doctorLogin() {
        //   console.log("doctor login");
        //   console.log(this.data.veriCode);
        //   if(this.data.veriCode != 'vesslink'){
        //     this.onClose();
        //     console.log("验证码错误，请重新输入");
        //     // Message.success({
        //     //   context: this,
        //     //   offset: [20, 32],
        //     //   duration: 5000,
        //     //   content: '验证码错误，请重新输入',
        //     // });
        //     return;
        //   }
        console.log("doctor login");
        wx.login({
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            success: (res) => {
                console.log(res);
                wx.request({ // 调用登录接口，获取用户登录凭证token
                    url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/auth?Action=LogIn`,
                    method: 'POST',
                    header: {
                        "Content-Type": "application/json"
                    },
                    data: {
                        "role": 1,
                        "wechatId": res.code,
                    },
                    success: (res) => { // 接口调用成功，获取token并缓存
                        console.log(res);
                        if (res.statusCode == 200) {
                            console.log('token', res.data.message.token);
                            wx.setStorageSync('token', res.data.message.token); // 将token进行缓存到'token'字段
                            this.getUserInfo();
                            wx.removeStorageSync('role')
                            wx.setStorageSync('role', "doctor");
                            if (!wx.getStorageSync("visitedPatients")) {
                                console.log(wx.getStorageSync("visitedPatients"))
                                wx.setStorageSync('visitedPatients', []);
                            }
                            setTimeout(() => {
                                wx.switchTab({
                                    url: '/pages/doctor/home/home',
                                })
                            }, 300)
                        } else {
                            wx.showModal({
                                title: '登陆错误',
                                content: "抱歉，我们将尽快检修",
                            });
                        }
                    },
                    fail: (res) => {
                        console.log("登录出现错误！");
                        wx.showModal({
                            title: '登陆错误',
                            content: '抱歉 我们将尽快检修',
                        })
                    }
                })
            }
        })
    },

    onVisibleChange(e) {
        this.setData({
            visible: e.detail.visible,
        });
    },
    // openPop(){
    //   this.setData({
    //     visible: true,
    //   });
    // },
    onClose() {
        this.setData({
            visible: false,
        });
    },
    handleInput(e) {
        this.setData({
            veriCode: e.detail.value // 将用户输入的内容保存到 data 中
        });
        // console.log(this.data.veriCode);
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})